package org.luxor.commons.log.config;

import org.luxor.commons.core.constant.FilterOrdered;
import org.luxor.commons.log.aspect.SysLogAspect;
import org.luxor.commons.log.event.SysLogListener;
import org.luxor.commons.log.filter.RequestLogFilter;
import org.luxor.commons.log.store.SysLogStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * 系统日志配置
 *
 * @author lengleng
 */
@EnableAsync
@Configuration
@ConditionalOnWebApplication
public class RequestLogAutoConfiguration {
    private static final Logger log = LoggerFactory.getLogger(SysLogStore.class);

    @Bean
    public FilterRegistrationBean<RequestLogFilter> requestLogFilterRegistration() {
        FilterRegistrationBean<RequestLogFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RequestLogFilter());
        registration.setOrder(FilterOrdered.REQUEST_LOG_FILTER_PRECEDENCE.getOrder());
        registration.addUrlPatterns("/*");
        return registration;
    }

    @Bean
    @ConditionalOnMissingBean(SysLogStore.class)
    public SysLogStore sysLogStore() {
        return sysLog -> log.info("系统操纵日志: {}", sysLog);
    }

    @Bean
    @ConditionalOnClass(SysLogStore.class)
    public SysLogListener sysLogListener(SysLogStore sysLogStore) {
        return new SysLogListener(sysLogStore);
    }

    @Bean
    public SysLogAspect sysLogAspect() {
        return new SysLogAspect();
    }
}
